package com.vanguard.commons.interceptor;

import com.vanguard.commons.utils.CookieUtils;
import com.vanguard.domain.User;
import com.vanguard.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Title: 登录拦截器
 * @Description:
 * @Author: vanguard
 * @Version: 1.0
 * @Date: 2018/11/22
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserService userService;

    /**
     * 微信appId
     */
    @Value("${appId}")
    private String appId;

    /**
     * 重定向的url域名
     */
    @Value("${url}")
    private String redirectUrl;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        //查询Cookie是否有openId
        String openId = CookieUtils.getCookieValue(request, "openId");
        //如果没有查询到，未登录状态，重定向到获取openId链接
        if(StringUtils.isBlank(openId)) {
            //重定向到获得openId链接
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId +"&redirect_uri=" + redirectUrl +"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
            response.sendRedirect(url);
            return false;
        }
        //查询是否第一次登陆
        User user = userService.getByOpenId(openId);
        if(user == null) {
            //重定向到输入姓名和身份证号页面
            response.sendRedirect( request.getContextPath() + "/user/toRegister");
            return false;
        }
        //放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
